<style scoped>
</style>
<template>
  <div class="box-request-info">
    <van-pull-refresh v-model="refresh_loading" @refresh="refresh" :disabled="!pull_refresh">
      <template v-if="info">
        <template v-if="$slots.default">
          <slot name="default" :info="info"/>
        </template>
        <PageBlock v-for="child in _children_" v-bind="child" :info="info"></PageBlock>
      </template>
      <van-empty v-show="!info&&finished&&!hidden_empty" description="暂无数据" />
    </van-pull-refresh>
  </div>
</template>

<script>

import {debounce, param_encode} from "@/js/s94_tool.js";
import {ajax} from "@/js/api_tool.js";
import PageBlock from "@/components/auto_import/PageBlock.vue";

/**请求列表
 * @prop {*}
 */
export default {
  _title_: '请求详情',
  _tip_: '请求接口后，以响应的data数据作为子组件的$info，仅获取一次',
  _head_img_: '',
  _group_: '容器组件',
  components: {PageBlock},
  props:{
    url: {
      type: String,
      _label_: '接口地址',
      _tip_: '详情数据获取的接口地址',
      _required_: true,
    },
    _children_: Array,

    data: [Object,String],
    pull_refresh: {
      type: Boolean,
      _label_: '下拉刷新',
      _tip_: '是否启用下拉刷新',
    },
    hidden_empty: {
      type: Boolean,
      _label_: '隐藏空状态',
      _tip_: '',
    },

    //回到方法
    load_before: Function,
    refresh_before: Function,
  },
  data(){
    return {
      info: null,

      loading: false,
      refresh_loading: false,
      finished: false,
    }
  },
  methods:{
    load: debounce(async function(){
      if (this.load_before && this.load_before()===false) return ;
      if (!this.url) return console.error('请求地址不存在');
      if (this.loading || this.finished) return;

      let url = this.url;
      let dataStr = param_encode(this.data);
      if (dataStr){
        url += (~url.indexOf('?') ? '&' : '?') + dataStr;
      }
      try {
        let res = await ajax(url);
        this.info = res.data;
      } catch (e) {
        // msg.fail(e.message); // ajax 中已经显示过错误信息了
      }
      setTimeout(()=>{
        this.loading=false;this.refresh_loading=false;
        this.finished = true;
      }, 20);
    }, 100),
    load_init(){
      this.loading=false;
      this.finished = false;
      this.load();
    },
    refresh(){
      if (this.refresh_before && this.refresh_before()===false) {
        this.refresh_loading=false;
        return;
      }
      this.load_init();
    },

  },
  watch: {
    url(){
      this.load_init();
    },
    data(v, oldV){
      this.load_init();
    }
  },
  computed:{},
  mounted(){
    this.load_init();
  }
}
</script>